package com.zychao.smex.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zychao.smex.db.service.BusinessService;
import com.zychao.smex.exception.CartNotFoundException;
import com.zychao.smex.po.Cart;

@SuppressWarnings("serial")
@WebServlet("/BuyServlet")
public class BuyServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		boolean b = isToken(request);
		if (b) {
			request.getSession().removeAttribute("token");

			String bookId = request.getParameter("bookId");
			Cart cart = (Cart) request.getSession().getAttribute("cart");
			if (cart == null) {
				cart = new Cart();
				request.getSession().setAttribute("cart", cart);
			}
			BusinessService service = new BusinessService();
			try {
				service.addToCart(bookId, cart);
			} catch (CartNotFoundException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("/WEB-INF/jsp/listCart.jsp").forward(request, response);
		} else {
			request.getRequestDispatcher("/WEB-INF/jsp/listCart.jsp").forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private boolean isToken(HttpServletRequest request) {
		String clientToken = request.getParameter("token");

		if (clientToken == null) {
			return false;
		}

		String serverToken = (String) request.getSession().getAttribute("token");
		if (serverToken == null) {
			return false;
		}

		if (!clientToken.equals(serverToken)) {
			return false;
		}

		return true;
	}
}
